import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { JwtService } from '@nestjs/jwt';
import { hash, verify } from 'argon2';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import * as nodemailer from 'nodemailer';
import { emailCode } from './dto/email-auth.dto';
import md5 from 'md5';
import { now } from 'lodash';
import { Cache } from 'cache-manager';
import { judgeEmailDto } from './dto/judge.auth.dto';

@Injectable()
export class AuthService {
  private transporter;
  constructor(
    private prisma: PrismaService,
    private jwt: JwtService,
    @Inject(CACHE_MANAGER) private cache: Cache,
  ) {
    this.transporter = nodemailer.createTransport({
      host: 'smtp.qq.com', // QQ 邮箱的 SMTP 服务器地址
      port: 465, // QQ 邮箱的 SMTP 服务器端口号
      secure: true,
      auth: {
        user: '2991519764@qq.com',
        pass: 'drwybhbqfsxedhed',
      },
    });
  }
  async create(dto: CreateAuthDto) {
    if (dto.gender == true) {
      const user = await this.prisma.user.create({
        data: {
          userName: dto.userName,
          passWord: await hash(dto.passWord),
          name: dto.name,
          gender: dto.gender,
          email: dto.email,
          avatar: 'uploads/1690959485037-2624999971.jpg',
        },
      });
      return this.token(user);
    } else {
      const user = await this.prisma.user.create({
        data: {
          userName: dto.userName,
          passWord: await hash(dto.passWord),
          name: dto.name,
          gender: dto.gender,
          email: dto.email,
          avatar: 'uploads/1690875759663-4287370809.jpg',
        },
      });
      return this.token(user);
    }
  }

  //生成token
  async token(user: any) {
    return {
      token: await this.jwt.signAsync({
        name: user.name,
        sub: user.id,
      }),
    };
  }
  //发送邮箱验证码
  async setEmailCode(email: emailCode, ip: any) {
    let code = String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
    const key = md5('capcha' + now() + ip);

    //将验证码保存下来
    await this.cache.set(key, code, 1000 * 60 * 5);
    const content = `<div style="background-color: #f0f0f0; padding: 20px;">

    <h1 style="color: #800000;">云漫API</h1>
    <p style="color: #800000;">尊敬的用户，您的短信验证码为：<span style="color: black; font-weight: bold;">${code}</span></p>
    <p style="color: #800000;">该验证码用于注册账号或者修改密码，有效期为5分钟。</p>
    <p style="color: #800000;">请勿泄露和转发此验证码，以保障您的账号安全。</p>
    <p style="color: #800000;">如非您本人操作，请忽略此邮件。</p>
</div></p>
    `;
    try {
      const mailOptions = {
        from: '2991519764@qq.com', // 发送方邮箱地址，一般和上面的邮箱一致
        to: email.email,
        subject: '云漫API(请不要回复此邮件)',
        html: content,
      };
      await this.transporter.sendMail(mailOptions);
      return {
        message: '邮箱发送成功',
        key,
      };
    } catch (error) {
      throw new Error('很抱歉验证码没有发送成功');
    }
  }
  //验证邮箱验证码
  async findOne(dto: judgeEmailDto) {
    const code = await this.cache.get(dto.key);
    if (code != dto.value) {
      throw new BadRequestException('验证码输入错误');
    } else {
      return {
        message: '验证码验证成功',
      };
    }
  }

  async login(dto: UpdateAuthDto) {
    const user = await this.prisma.user.findFirst({
      where: {
        userName: dto.userName,
      },
    });
    if (!(await verify(user.passWord, dto.passWord))) {
      delete user.passWord;
    }
    delete user.passWord;
    return {
      ...user,
      token: await this.jwt.signAsync({
        name: user.userName,
        sub: user.id,
      }),
    };
  }

  async remove(id: number) {
    const user = await this.prisma.user.delete({
      where: {
        id,
      },
    });
    if (user) {
      return {
        message: '删除用户成功',
      };
    }
  }
}
